/*
 * Copyright (c) 2010 by Cristian Maglie <c.maglie@bug.st>
 * SPI Master library for arduino.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of either the GNU General Public License version 2
 * or the GNU Lesser General Public License version 2.1, both as
 * published by the Free Software Foundation.
 */

#ifndef _SPI_H_INCLUDED
#define _SPI_H_INCLUDED

#include <stdio.h>
#include "core.h"

#define SSIG 0x80
#define SPEN 0x40
#define DORD 0x20
#define MSTR 0x10
#define SPIE 0x80
#define SPIF 0x80
#define WCOL 0x40

#define SPI_CLOCK_DIV4 0x00
#define SPI_CLOCK_DIV16 0x01
#define SPI_CLOCK_DIV64 0x02
#define SPI_CLOCK_DIV128 0x03

#define SPI_MODE0 0x00
#define SPI_MODE1 0x04
#define SPI_MODE2 0x08
#define SPI_MODE3 0x0C

#define SPI_MODE_MASK 0x0C  // CPOL = bit 3, CPHA = bit 2 on SPCR
#define SPI_CLOCK_MASK 0x03  // SPR1 = bit 1, SPR0 = bit 0 on SPCR

class SPIClass
{
public:
    inline static byte transfer(byte _data);

    // SPI Configuration methods

    inline static void attachInterrupt();
    inline static void detachInterrupt(); // Default

    static void begin(); // Default
    static void end();

    static void setBitOrder(uint8_t);
    static void setDataMode(uint8_t);
    static void setClockDivider(uint8_t);
};

extern SPIClass SPI;

byte SPIClass::transfer(byte _data)
{
    //Function transfer will NOT operate SS
    //You should do it yourself.
    SPDAT = _data;

    while(!(SPSTAT & SPIF));

    SPSTAT = (SPIF | WCOL); //Assign 1 to CLEAR the bits. It's wired, but correct;
    return SPDAT;
}

void SPIClass::attachInterrupt()
{
    AUXR |= SPIE;
}

void SPIClass::detachInterrupt()
{
    AUXR &= ~SPIE;
}

#endif
